package bb

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.Point
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.*
import android.widget.ImageButton
import android.widget.SeekBar
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.camera.core.*
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModelProviders
import com.blankj.utilcode.util.PathUtils
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import oa.lla.cca.R
import com.clean.scanlibrary.bean.CurrencyInfoBean
import com.clean.scanlibrary.bean.DiscernInfoBean
import com.clean.scanlibrary.bean.DiscernTokenBean
import com.clean.scanlibrary.bean.WordInfoBean
import com.clean.scanlibrary.camera.utils.FileUtil
import com.clean.scanlibrary.camera.utils.Utils
import com.clean.scanlibrary.camera.utils.YuvToRgbConverter
import bc.EZ
import bc.CF
import com.clean.scanlibrary.dialog.BlackAndWhiteDialog
import com.clean.scanlibrary.dialog.CameraPremissDialog
import com.clean.scanlibrary.dialog.DiscernTipsDialog
import com.clean.scanlibrary.dialog.LoadingDialog
import com.clean.scanlibrary.http.DiscernViewMode
import com.clean.scanlibrary.http.HttpApi
import bd.CN
import com.clean.scanlibrary.utils.SPreference
import com.google.common.util.concurrent.ListenableFuture
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.XXPermissions
import org.greenrobot.eventbus.EventBus
import java.io.File
import java.nio.file.Files
import java.nio.file.Paths
import java.util.*
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit


/**
 *
 * setLinearZoom: 通过从0f到1.0f的线性变焦值设置当前变焦。LinearZoom 0f表示最小变焦，而LinearZoom 1.0f表示最大变焦。
 * 线性缩放的优点是，它确保视场(FOV)随线性缩放值线性变化，用于滑块UI元素(而setZoomRatio适用于捏缩放手势)
 *
 * @author zhangdecheng ceshi tijaio
 */
class CD : AppCompatActivity() {
    private var imageCapture: ImageCapture? = null
    private var mCameraControl: CameraControl? = null
    private var mCameraInfo: CameraInfo? = null
    private var focusView: CF? = null
    private var isInfer = false
    private var imageRotationDegrees: Int = 0
    private var flashMode: Int = ImageCapture.FLASH_MODE_OFF
    private var photoViewButton:ImageButton? = null
    private var linearZoom: SeekBar? = null
    private var lightZoom: SeekBar? = null
    private var viewFinder:PreviewView? = null
    // 使用后摄像头
    private var cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
    private var hasGetPermission by SPreference("ISHASCAMERAPERMISS",false)
    private var hasRefusePermission by SPreference("ISREFUSECAMERAPERMISS",false)
    private lateinit var cameraExecutor: ExecutorService
    private lateinit var bitmapBuffer: Bitmap
    private lateinit var converter: YuvToRgbConverter
    private var loadingDialog: LoadingDialog? = null
    private var viewMode: DiscernViewMode? = null
    private var discernTokenBean : DiscernTokenBean? = null
    private var viewType:Int = 0
    private var currentPic:String = ""
    companion object {
        const val SEEK_BAR_MAX = 100.0
        const val LIGHT_SEEK_BAR_MAX = 255.0
        const val LIGHT_INIT = 0.5f
        const val LINEAR_ZOOM_MAX = 1.0
        const val REQUEST_CODE_PERMISSIONS = 10
        var REQUIRED_PERMISSIONS =
            arrayOf(Manifest.permission.MANAGE_EXTERNAL_STORAGE,Manifest.permission.CAMERA)
        private const val TAG = "CameraMagnifygActivity"

        const val VIEW_FROM_BOTANY = 1 //植物识别 (快用完了)
        const val VIEW_FROM_GARDEN = 2 //果蔬识别  用完
        const val VIEW_FROM_INGREDIENT = 3 //菜品识别 用完
        const val VIEW_FROM_ANIMAL = 4 //动物识别
        const val VIEW_FROM_WORD = 5 //文字识别
        const val VIEW_FROM_CURRENCY = 6//货币识别
        const val VIEW_FROM_FORMULA = 7 //数字扫描
        const val VIEW_FROM_COLOURIZE = 8//图片黑白上色 用完
        const val VIEW_FROM_PIC_STYLE = 9//图像风格转换 用完
        const val VIEW_FROM_PIC_PEOPLE = 10//人像动漫化 用完
        const val VIEW_FROM_RED_WINE = 11//红酒识别
        const val VIEW_FROM_DEHAZE = 12//图像去雾 用完
        const val VIEW_FROM_CONTRAST_ENHANCE = 13//图像对比度增强 用完
        const val VIEW_FROM_REMOVE_MOIREURL = 14//去除摩尔纹 用完
        const val VIEW_FROM_BODY_SCAN= 15 //物体识别 三万次
        const val VIEW_FROM_CAR_SCAN= 16 //车辆外观损伤识别
        const val VIEW_FROM_CAR_DETECTION_SCAN= 17 //车辆检测

        const val VIEWFROMTYPE = "viewFromType"; //0默认是文字识别  VIEW_FROM_BOTANY植物识别  VIEW_FROM_GARDEN果蔬识别 VIEW_FROM_INGREDIENT菜品识别  VIEW_FROM_ANIMAL 动物识别


        fun startNewCameraMagnifygActivity(context: Context,viewFromType:Int){
            val intent:Intent = Intent(context,CD::class.java)
            intent.putExtra(VIEWFROMTYPE,viewFromType)
            context.startActivity(intent)
        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_camera_layout)


        cameraExecutor = Executors.newSingleThreadExecutor()
        // 把图像数据转换为RGB格式图像
        converter = YuvToRgbConverter(this)

        if(hasRefusePermission){
            Toast.makeText(this,"用户拒绝权限申请，请到设置里打开相关权限",Toast.LENGTH_SHORT).show()
            finish()
            return
        }


        initPremissList()

        viewType = intent.getIntExtra(VIEWFROMTYPE,0)
        initData()
        immersionStatusBar()
        initListener()
        linearZoom = findViewById(R.id.linear_zoom)
        lightZoom = findViewById(R.id.light_zoom)
        viewFinder = findViewById<PreviewView>(R.id.viewFinder)
        linearZoom?.progress = 0
        val light = LIGHT_INIT
        setWindowBrightness(light)
        lightZoom?.progress = (light * LIGHT_SEEK_BAR_MAX).toInt()
        // 对焦框控件、
        focusView = findViewById(R.id.focus_view)


        // 请求权限
        if (hasGetPermission) {
            startCamera()
        } else {
            val permissDialog = CameraPremissDialog(this, R.style.dialog)
            permissDialog.show()
            permissDialog.setOnDialogClickListener(object : CameraPremissDialog.OnDialogClickListener{
                override fun onAgree() {
                    toPremiss()
                }
                override fun onCancel() {
                    Toast.makeText(this@CD, "没有相机授权与本地存储权限授权，无法使用！", Toast.LENGTH_SHORT).show()
                    finish()
                }
            })
        }

        // 打开自定义相册
        photoViewButton = findViewById<ImageButton>(R.id.photo_view_button)

    }

    private fun initPremissList() {

//        REQUIRED_PERMISSIONS = if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.R){
//            arrayOf(Manifest.permission.MANAGE_EXTERNAL_STORAGE,Manifest.permission.CAMERA)
//        }else{
        REQUIRED_PERMISSIONS = arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.CAMERA)
//        }

    }


    private fun toPremiss(){
        XXPermissions.with(this) // 不适配 Android 11 可以这样写
            //.permission(Permission.Group.STORAGE)
            // 适配 Android 11 需要这样写，这里无需再写 Permission.Group.STORAGE
            .permission(REQUIRED_PERMISSIONS)
            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: List<String>, all: Boolean) {
                    if (all) {
                        hasGetPermission = true
                        startCamera()
                    }
                }

                override fun onDenied(permissions: List<String>, never: Boolean) {
                    hasRefusePermission = true
                    if (never) {
                        Toast.makeText(this@CD, "被永久拒绝授权，请手动授予存储权限！", Toast.LENGTH_SHORT).show()
                        XXPermissions.startPermissionActivity(this@CD, permissions)
                    } else {
                        Toast.makeText(this@CD, "没有相机授权与本地存储权限授权，无法使用！", Toast.LENGTH_SHORT).show()
                    }

                    finish()
                }
            })
    }









    private fun initListener() {
        findViewById<View>(R.id.back)?.setOnClickListener {
            finish()
        }


        lightZoom?.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                val current = (progress / LIGHT_SEEK_BAR_MAX).toFloat()
                setWindowBrightness(current)
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
            }

        })


        linearZoom?.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                val current = (progress / SEEK_BAR_MAX).toFloat()
                Log.e(
                    TAG,
                    "onProgressChanged: progress:$progress, current:$current, mCameraControl: $mCameraControl"
                )
                mCameraControl?.setLinearZoom(current)
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
            }
        })

        // 点击拍照
        findViewById<ImageButton>(R.id.camera_capture_button).setOnClickListener { takePhoto() }
        findViewById<TextView>(R.id.camera_capture_button_2).setOnClickListener { takePhoto() }

        // 切换摄像头
        findViewById<ImageButton>(R.id.camera_switch_button).setOnClickListener {
            cameraSelector = if (CameraSelector.DEFAULT_FRONT_CAMERA == cameraSelector) {
                CameraSelector.DEFAULT_BACK_CAMERA
            } else {
                CameraSelector.DEFAULT_FRONT_CAMERA
            }
            // 重启相机
            startCamera()
        }

        photoViewButton?.setOnClickListener {
            val intent = Intent(this, EY::class.java)
            startActivity(intent)
        }



        // 切换闪光灯模式
        findViewById<ImageButton>(R.id.flash_switch_button).setOnClickListener {
            when (flashMode) {
                ImageCapture.FLASH_MODE_OFF -> {
                    flashMode = ImageCapture.FLASH_MODE_ON
                    findViewById<ImageButton>(R.id.flash_switch_button).setImageResource(R.drawable.open_flash)
                }
                ImageCapture.FLASH_MODE_ON -> {
                    flashMode = ImageCapture.FLASH_MODE_AUTO
                    findViewById<ImageButton>(R.id.flash_switch_button).setImageResource(R.drawable.auto_flash)
                }
                ImageCapture.FLASH_MODE_AUTO -> {
                    flashMode = ImageCapture.FLASH_MODE_OFF
                    findViewById<ImageButton>(R.id.flash_switch_button).setImageResource(R.drawable.stop_flash)
                }
            }
            // 重启相机
            startCamera()
        }

    }


    /**
     * 沉浸式状态栏
     */
    private fun immersionStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            val window: Window = window
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
            // 沉浸式状态栏
            window.decorView.systemUiVisibility =
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
            // 状态栏改为透明
            window.statusBarColor = Color.TRANSPARENT
        }
    }


    private fun initData(){
        loadingDialog =
            LoadingDialog(this, R.style.dialog)
        loadingDialog?.show()

        viewMode = ViewModelProviders.of(this).get(DiscernViewMode::class.java)
        //初始化获取Token
        when(viewType){
            //文字识别类型
            VIEW_FROM_WORD,
            VIEW_FROM_FORMULA->{
                viewMode?.getDiscernToken(HttpApi.discernWordsAPIKey,HttpApi.discernWordsSecretKey)
            }

            //图片特效类型
            VIEW_FROM_PIC_PEOPLE,
            VIEW_FROM_COLOURIZE,
            VIEW_FROM_REMOVE_MOIREURL,
            VIEW_FROM_DEHAZE,
            VIEW_FROM_CONTRAST_ENHANCE->{
                viewMode?.getDiscernToken(HttpApi.discernPicsAPIKey,HttpApi.discernPicSecretKey)
            }
            //图文识别类型
           else ->
            viewMode?.getDiscernToken(HttpApi.discernAPIKey,HttpApi.discernSecretKey)

        }

        //token请求返回
        viewMode?.getTokenLiveData?.observe(this
        ) { t ->
            loadingDialog?.dismiss()
            discernTokenBean = t
        }

        //上传文字扫描返回结果
        viewMode?.getWordsLiveData?.observe(this) { t ->
            loadingDialog?.dismiss()
            if (t != null) {
                showWordsDialog(t!!)
            } else {
                Toast.makeText(this@CD, "获取信息失败", Toast.LENGTH_SHORT).show()
            }
        }
        //上传货币扫描结果
        viewMode?.getCurrencyLiveData?.observe(this) { t ->
            loadingDialog?.dismiss()
            if (t != null) {
                when (viewType) {
                    //货币识别
                    VIEW_FROM_CURRENCY -> {
                        showCurrencyDialog(t)
                    }
                    else -> {
                        val picDialo: BlackAndWhiteDialog = BlackAndWhiteDialog(this,R.style.dialog)
                        picDialo.showPicView(currentPic,t.image)
                        picDialo.show()
                    }
                }
            } else {
                Toast.makeText(this@CD, "获取信息失败", Toast.LENGTH_SHORT).show()
            }
        }

        //红酒识别
        viewMode?.getRedWineLiveData?.observe(this){ t->
            loadingDialog?.dismiss()
            if (t!=null){
                val sb = java.lang.StringBuilder()
                if (TextUtils.isEmpty(t.wineNameCn)){
                    sb.append("名称：未知\n")
                }else{
                    sb.append("名称："+t.wineNameCn+"\n")
                }

                if (t.hasdetail == 1){
                    sb.append("酒类型："+t.classifyByColor+"\n")
                    sb.append("产区中文名："+t.subRegionCn+"\n")
                    sb.append("色泽："+t.color+"\n")
                    sb.append("酒庄中文名："+t.wineryCn+"\n")
                    sb.append("产区中文名："+t.regionCn+"\n")
                    sb.append("简介："+t.description+"\n")
                }else{
                    sb.append("简介：暂无相关信息\n")
                }
                val bean:CurrencyInfoBean = CurrencyInfoBean(sb.toString(),0,"","","","","","")
                showCurrencyDialog(bean)
            }
        }


        //拍照后走网络识别
        viewMode?.getPicInfoLiveData?.observe(this
        ) { t ->
            loadingDialog?.dismiss()
            if (t != null) {
                if (viewType == VIEW_FROM_BODY_SCAN){
                    //物体识别
                    CE.startBodyScanActivity(this,t,currentPic)
                }else{
                    showTipsDialog(t)
                }
            }
        }

        //接口异常提示
        viewMode?.posHttpError?.observe(this
        ) {
            loadingDialog?.dismiss()
            Toast.makeText(this,it,Toast.LENGTH_SHORT).show()}
    }



    //本地拍照文件进行Base64编码
    @RequiresApi(Build.VERSION_CODES.O)
    fun getFileContentAsBase64(path: String?): String? {
        val b: ByteArray = Files.readAllBytes(Paths.get(path))
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Base64.getEncoder().encodeToString(b)
        } else {
            ""
        }
    }

    private fun toUploadPrc(path:String){
        currentPic = path
        loadingDialog?.show()
        if(TextUtils.isEmpty(discernTokenBean?.access_token) || TextUtils.isEmpty(path)){
            ToastUtils.showShort("识别异常，请稍后重试。")
            return
        }

        when(viewType){
            VIEW_FROM_WORD ->{
                //文字扫描
                viewMode?.toUploadWordInfo(discernTokenBean?.access_token!!,path,viewType)
            }
            VIEW_FROM_FORMULA ->{
                //数字扫描
                viewMode?.toUploadFormulaInfo(discernTokenBean?.access_token!!,path,viewType)
            }

            VIEW_FROM_CURRENCY->{
                //货币识别
                viewMode?.toUploadCurrency(discernTokenBean?.access_token!!,path,viewType)
            }

            //黑白上色
            VIEW_FROM_COLOURIZE->{
                viewMode?.getPicspecial(discernTokenBean?.access_token!!,path,viewType,HttpApi.discerncolourizeUrl)
            }

            //人物漫画
            VIEW_FROM_PIC_PEOPLE->{
                viewMode?.getPicspecial(discernTokenBean?.access_token!!,path,viewType,HttpApi.stylePeopleUrl)
            }

           //图像去雾
            VIEW_FROM_DEHAZE->{
                viewMode?.getPicspecial(discernTokenBean?.access_token!!,path,viewType,HttpApi.dehazeUrl)
            }

            //图像对比度增强®
            VIEW_FROM_CONTRAST_ENHANCE->{
                viewMode?.getPicspecial(discernTokenBean?.access_token!!,path,viewType,HttpApi.contrast_enhanceUrl)
            }


           //去除摩尔纹
            VIEW_FROM_REMOVE_MOIREURL->{
                viewMode?.getPicspecial(discernTokenBean?.access_token!!,path,viewType,HttpApi.remove_moireUrl)
            }


            //红酒识别
            VIEW_FROM_RED_WINE->{
                viewMode?.getRedWine(discernTokenBean?.access_token!!,path,viewType)
            }
            else->{
                viewMode?.toUploadPicInfo(discernTokenBean?.access_token!!,path,viewType)
            }
        }
    }


    //调用接口识别之后展示一个提示信息弹唱（暂时定义一个弹窗）
    private fun showTipsDialog(dataList:ArrayList<DiscernInfoBean>){
        val dialog : DiscernTipsDialog = DiscernTipsDialog(this,R.style.dialog)
        dialog.setInfoData(dataList,currentPic)
        dialog.show()
    }


    //调用接口识别之后展示一个提示信息弹唱（暂时定义一个弹窗）
    private fun showWordsDialog(dataBean:WordInfoBean){
        val dialog : DiscernTipsDialog = DiscernTipsDialog(this,R.style.dialog)
        dialog.setWordsInfoData(dataBean,currentPic)
        dialog.show()
    }


    private fun showCurrencyDialog(dataBean: CurrencyInfoBean){
        val dialog= DiscernTipsDialog(this,R.style.dialog)
        dialog.setCurrencyData(dataBean,currentPic)
        dialog.show()
    }

    override fun onResume() {
        super.onResume()
        // 显示最新的图像
        val images = Utils.getFilesAllName(PathUtils.getExternalAppPicturesPath())
        if (images.isNotEmpty()) {
            Glide.with(this@CD)
                .load(images[images.size - 1])
                .apply(RequestOptions.circleCropTransform())
                .into(photoViewButton!!)
        } else {
            Glide.with(this@CD)
                .load(R.drawable.camera_ic_photo)
                .apply(RequestOptions.circleCropTransform())
                .into(photoViewButton!!)
        }
    }

    // 启动相机
    private fun startCamera() {
        val cameraProviderFuture = ProcessCameraProvider.getInstance(this@CD)
        cameraProviderFuture.addListener({
            // 绑定生命周期
            val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()

            // 设置相机支持预览
            val preview = Preview.Builder().build()
            preview.setSurfaceProvider(viewFinder?.surfaceProvider);

            // 设置相机支持拍照
            imageCapture = ImageCapture.Builder()
                // 设置闪光灯
                .setFlashMode(flashMode)
                // 设置照片质量
                .setCaptureMode(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY)
                .build()

            // 设置相机支持图像分析
            val imageAnalysis = ImageAnalysis.Builder()
                .setTargetAspectRatio(AspectRatio.RATIO_4_3)
                .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
                .build()

            // 实时获取图像进行分析
            imageAnalysis.setAnalyzer(ContextCompat.getMainExecutor(this)) { image ->
                if (isInfer) {
                    // 执行人脸检测
                    infer(image)
                }
            }

            try {
                // 在重新绑定之前取消绑定用例
                cameraProvider.unbindAll()

                // 将用例绑定到摄像机
                val camera: Camera = cameraProvider.bindToLifecycle(
                    this,
                    cameraSelector,
                    preview,
                    imageCapture,
                    imageAnalysis
                )
                // 相机控制，如点击
                mCameraControl = camera.cameraControl
                mCameraInfo = camera.cameraInfo
                initCameraListener()
            } catch (exc: Exception) {
                Log.e(TAG, "Use case binding failed", exc)
            }

        }, ContextCompat.getMainExecutor(this))
    }

    // 人脸检测
    @SuppressLint("UnsafeExperimentalUsageError", "WrongViewCast", "UnsafeOptInUsageError")
    private fun infer(image: ImageProxy) {
        if (!::bitmapBuffer.isInitialized) {
            imageRotationDegrees = image.imageInfo.rotationDegrees
            Log.d("测试", "方向：$imageRotationDegrees")
            bitmapBuffer = Bitmap.createBitmap(image.width, image.height, Bitmap.Config.ARGB_8888)
        }

        // 将图像转换为RGB，并将其放在bitmapBuffer
        image.use { converter.yuvToRgb(image.image!!, bitmapBuffer) }

        // 画框
        val boxPre:View = findViewById<View>(R.id.box_prediction)
        (boxPre.layoutParams as ViewGroup.MarginLayoutParams).apply {
            topMargin = 20
            leftMargin = 30
            width = 400
            height = 500
        }
    }

    // 拍照
    private fun takePhoto() {
        // 保证相机可用
        val imageCapture = imageCapture ?: return
        val path = getExternalFilesDir(null)?.absolutePath
        val photoFile = File(path, ""+System.currentTimeMillis()+".png")
        if (photoFile.exists()){
            photoFile.delete()
        }
        photoFile.createNewFile()
        // 创建包含文件和metadata的输出选项对象
        val outputOptions = ImageCapture.OutputFileOptions.Builder(photoFile).build()

        // 设置图像捕获监听器，在拍照后触发
        imageCapture.takePicture(
            outputOptions,
            ContextCompat.getMainExecutor(this),
            object : ImageCapture.OnImageSavedCallback {
                override fun onError(exc: ImageCaptureException) {
                    Log.e(TAG, "Photo capture failed: ${exc.message}", exc)
                }

                override fun onImageSaved(output: ImageCapture.OutputFileResults) {
                    val fileSize = FileUtil.getFileSize(photoFile.absolutePath)
                    val compressQuality:String = FileUtil.compressQuality(this@CD,photoFile.absolutePath)
                    val fileSize2 = FileUtil.getFileSize(compressQuality)
                    Log.i("HttpManager","压缩前"+fileSize+"压缩后"+fileSize2)
                    if (viewType == VIEW_FROM_PIC_STYLE){
                        CN.intentPicStyleActivity(this@CD,compressQuality)
                        finish()
                        return
                    }

                    toUploadPrc(compressQuality)
                }
            })
    }

    // 相机点击等相关操作监听
    private fun initCameraListener() {
        val cameraXPreviewViewTouchListener = EZ(this)

        cameraXPreviewViewTouchListener.setCustomTouchListener(object :
            EZ.CustomTouchListener {
            // 放大缩小操作
            override fun zoom(delta: Float) {
            }

            // 点击操作
            override fun click(x: Float, y: Float) {
                Log.d(TAG, "单击")
                val factory = viewFinder?.meteringPointFactory
                // 设置对焦位置
                val point = factory?.createPoint(x, y)
                val action = FocusMeteringAction.Builder(point!!, FocusMeteringAction.FLAG_AF)
                    // 3秒内自动调用取消对焦
                    .setAutoCancelDuration(3, TimeUnit.SECONDS)
                    .build()
                // 执行对焦
                focusView!!.startFocus(Point(x.toInt(), y.toInt()))
                val future: ListenableFuture<*> = mCameraControl!!.startFocusAndMetering(action)
                future.addListener({
                    try {
                        // 获取对焦结果
                        val result = future.get() as FocusMeteringResult
                        if (result.isFocusSuccessful) {
                            focusView!!.onFocusSuccess()
                        } else {
                            focusView!!.onFocusFailed()
                        }
                    } catch (e: java.lang.Exception) {
                        Log.e(TAG, e.toString())
                    }
                }, ContextCompat.getMainExecutor(this@CD))
            }

            // 双击操作
            override fun doubleClick(x: Float, y: Float) {

            }

            override fun longPress(x: Float, y: Float) {
//                Log.d(Companion.TAG, "长按")
            }
        })
        // 添加监听事件
        viewFinder?.setOnTouchListener(cameraXPreviewViewTouchListener)
    }

    override fun onDestroy() {
        super.onDestroy()
        // 关闭相机
        if (cameraExecutor!=null){
            cameraExecutor.shutdown()
        }

    }






    private fun setWindowBrightness(brightness: Float) {
        val window = window
        val lp = window.attributes
        lp.screenBrightness = brightness
        window.attributes = lp
    }

    private fun getWindowBrightness(): Float {
        val window = window
        val lp = window.attributes
        return lp.screenBrightness
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            EventBus.getDefault().post("saomiao_back")
            finish()
            return true
        }
        return super.onKeyDown(keyCode, event)
    }
}